﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;

namespace crm_web.Controls
{
	public class SitemapPage
	{
		public string URL { get; set; }

		/// <summary>
		/// * will allow all users.
		/// ? will allow all logged in users
		/// a specific role name will only allow users in that role. Uses "Or" logic.
		/// </summary>
		public List<string> Roles { get; set; }
		public string DisplayText { get; set; }
		public string DescriptionText { get; set; }

		public SitemapPage Parent { get; set; }
		private List<SitemapPage> Children { get; set; }
		public void AddChild(SitemapPage child)
		{
			child.Parent = this;
			Children.Add(child);
		}

		public bool IsRoot
		{
			get { return Parent == null; }
		}
		public bool HasChildren
		{
			get { return Children.Count > 0; }
		}
		public bool IsPage
		{
			get { return URL.Contains(".aspx"); }
		}
		public int Level
		{
			get
			{
				if(IsRoot) return 0;
				return Parent.Level + 1;
			}
		}

		public bool AllowsUser()
		{
			if (Roles.Count == 0) return true;
			if (Roles.Contains("*")) return true;
			if (Roles.Contains("?"))
			{
				if(HttpContext.Current.User.Identity.IsAuthenticated) return true;
			}
			foreach (var role in Roles)
			{
				if (HttpContext.Current.User.IsInRole(role)) return true;
			}
			return false;
		}

		public SitemapPage()
		{
			URL = "";
			Roles = new List<string>();
			DisplayText = "";
			DescriptionText = "";
			Parent = null;
			Children = new List<SitemapPage>();
		}

		public string ToLink()
		{
			const string format = "<a href='{0}' title='{1}'>{2}</a>";
			return String.Format(format, URL, DescriptionText, DisplayText);
		}

		public string ToNonLinkLabel()
		{
			const string format = "<span title='{0}'>{1}</a>";
			return String.Format(format, DescriptionText, DisplayText);
		}

		public string ToLineItem()
		{
			const string format = "<li class='NavMenu_LI_Lv{0}'>{1}</li>";
			return String.Format(format, Level, ToLink());
		}

		

		public string ToBulletedList()
		{
			if (!HasChildren) return ToLineItem();

			var list = new StringBuilder();

			if (!IsRoot)
			{
				list.AppendLine(String.Format("<li class='NavMenu_LI_Lv{0}'>", Level));

				if (IsPage) list.AppendLine(ToLink());
				else list.AppendLine(ToNonLinkLabel());
			}

			list.AppendLine("<ul class='NavMenu_UL_Lv" + Level + "'>");
			foreach (var child in Children)
			{
				if (child.AllowsUser()) list.AppendLine(child.ToBulletedList());
			}
			list.AppendLine("</ul>");

			if (!IsRoot) list.AppendLine("</li>");

			return list.ToString();
		}

	}
}